import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

@WebServlet("/ShowRequest2")
public class ShowRequest2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        StringBuilder result = new StringBuilder();
        result.append(req.getProtocol());//获取http协议版本号
        result.append("<br>");
        result.append(req.getMethod());//获取http请求的方法
        result.append("<br>");
        result.append(req.getRequestURI());//获取URL(content path,对应注解写的路径)
        result.append("<br>");
        result.append(req.getQueryString());//获取query string
        result.append("<br>");
        result.append(req.getContextPath());//获取路径
        result.append("<br>");

        //获取所有的header
        result.append("==============<br>");
        //header是一个枚举类型的，所以要用相对应的类型及逆行接收
        Enumeration<String> headerNames = req.getHeaderNames();
        while (headerNames.hasMoreElements()) {//枚举类型就是这样的语法格式
            String headerName = headerNames.nextElement();//获取key
            String headerValue = req.getHeader(headerName);//获取key对应的值
            result.append(headerName + ":" + headerValue + "<br>");
        }
        //把请求的数据写回到响应中去，才能在浏览器中进行显示
        //在响应中设置body的类型，方便浏览器进行解析
        resp.setContentType("text/html;charset=utf8");
        resp.getWriter().write(result.toString());
    }
}
